import { defineComponent, inject, onMounted, reactive, ref, computed, onUnmounted } from 'vue';
import Sortable from 'sortablejs';
import { useRoute } from 'vue-router';
import type { UploadRequestOptions, uploadFile, uploadFiles } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useExpose } from '@/components/zw/utils/index';
import './style/cardConfig.scss';

import { uploadFile2 } from '@/api/common';

import plusIcon from './icon/plus-icon.svg';
import removeIcon from './icon/remove-icon.svg';
import optionIcon from './icon/option-icon.svg';

export default defineComponent({
    name: 'ControlCard',
    directives: {
        focus: {
            mounted: el => {
                const input = el?.querySelector('input') || el?.querySelector('textarea');
                input && input.focus();
            }
        }
    },
    props: {
        controlCardColumns: {
            type: Array,
            default: () => []
        },
        form_desc: {
            type: String
        }
    },

    setup(this, props, ctx: any) {
        const route: any = useRoute();
        const routeType = computed(() => {
            // 跳转类型
            return route.query.type;
        });
        const isViewDisabled = computed(() => {
            // 查看下禁用
            return routeType.value === 'view';
        });
        // 上传文件
        const doUpload = async (file: UploadRequestOptions) => {
            const params = {
                file: file.file,
                fileName: file.file.name
            };
            const res: any = await uploadFile2(params);
            return res;
        };
        /* 表单标题 */
        const showInput = ref<boolean>(false);
        const form_desc = computed({
            get: () => {
                return props.form_desc;
            },
            set: v => {
                ctx.attrs['onUpdate:form_desc']?.(v);
            }
        });
        const basicInfo: any = inject('basicInfo');
        /* 表单标题 */
        /* 控件列表 */
        const setCurrentItem: any = inject('setCurrentItem');
        const removeFormDataItem: any = inject('removeFormDataItem');
        const currentId = ref();
        useExpose({
            currentId
        });
        const handleCardClick = (v: any, i: number) => {
            currentId.value = v.id;
            setCurrentItem(v, i);
        };

        /* 渲染控件列表 */
        const renderEmpty = () => {
            return <div class="config-card-empty">请点击左侧按钮添加控件～</div>;
        };
        const renderShowContentList = (columns: any) => {
            return (
                // 收集表表单
                <div class="config-card-list" id="config-card-list">
                    {columns?.length
                        ? columns.map((v: any, i: number) => {
                              return (
                                  <div
                                      class={{
                                          'config-card__actived': currentId.value === v.id,
                                          'config-card-item': true
                                      }}
                                      key={v.id}
                                      onMousedown={() => handleCardClick(v, i)}>
                                      <div class="config-card-item__title">
                                          <div onClick={() => (v.is_title_write = true)}>
                                              <span class="config-card-item__title__index">
                                                  <span class="is-require">
                                                      {v.is_require && v.type !== 'carousel' ? '*' : ''}
                                                  </span>
                                                  {`${i + 1}`.padStart(2, '0')}
                                              </span>
                                              {v.is_title_write ? (
                                                  <el-input
                                                      disabled={isViewDisabled.value}
                                                      v-model={v.form_change_title}
                                                      placeholder="请输入标题"
                                                      maxlength="20"
                                                      v-focus
                                                      show-word-limit
                                                      onMousedown={handleStopPropagation}
                                                  />
                                              ) : (
                                                  v.form_change_title || v.form_title || '请输入标题'
                                              )}
                                          </div>
                                          <div class="drag-item">
                                              <img src={optionIcon} />
                                          </div>
                                      </div>
                                      <div class="config-card-item__desc">
                                          <div onClick={() => (v.is_desc_write = true)}>
                                              {v.is_desc_write ? (
                                                  <el-input
                                                      v-model={v.form_desc}
                                                      placeholder="请输入描述"
                                                      v-focus
                                                      maxlength="20"
                                                      show-word-limit
                                                      disabled={isViewDisabled.value}
                                                      onMousedown={handleStopPropagation}
                                                  />
                                              ) : (
                                                  v.form_desc || '请输入描述'
                                              )}{' '}
                                          </div>
                                      </div>
                                      <div class="config-card-item__input">{renderControlInput(v)}</div>
                                      {!isViewDisabled.value && currentId.value === v.id && v.type !== 'carousel' && (
                                          <div class="config-card-item__attr">
                                              <div v-if={v.type !== 'carousel'}>
                                                  <label class="config-card-item__attr__row">
                                                      <el-checkbox
                                                          v-model={v.is_require}
                                                          disabled={v.type == 'mobile'}
                                                      />{' '}
                                                      <span>必填</span>
                                                  </label>
                                              </div>
                                              <div
                                                  class="config-card-item__attr__row"
                                                  onClick={() => removeFormDataItem(i)}>
                                                  <img src="/static/delete.png" /> <span>删除</span>
                                              </div>
                                          </div>
                                      )}
                                      {!isViewDisabled.value && currentId.value === v.id && v.type == 'carousel' && (
                                          <div class="config-card-item__attr">
                                              <div
                                                  class="config-card-item__attr__row"
                                                  onClick={() => removeFormDataItem(i)}>
                                                  <img src="/static/delete.png" /> <span>删除</span>
                                              </div>
                                          </div>
                                      )}
                                  </div>
                              );
                          })
                        : renderEmpty()}
                </div>
            );
        };

        /* 选项卡增删 */
        const addOption = (v: any) => {
            if (v.options_list.length >= 20) return ElMessage.warning('最多添加20个');
            v.options_list.push({
                value: '',
                tags_list: [],
                is_option_write: true
            });
        };
        const removeOption = (v: any, op_index: number, optionItem: any) => {
            v.options_list.splice(op_index, 1);
            props.controlCardColumns.forEach((item: any) => {
                for (const index in item.rules_list) {
                    const ruleItem = item.rules_list[index];
                    if (ruleItem.related_key === v.key) {
                        const relaIndex = ruleItem.related_value.findIndex(
                            (relaItem: any) => relaItem === optionItem.value
                        );
                        if (relaIndex >= 0) {
                            ruleItem.related_value.splice(relaIndex, 1);
                        }
                    }
                }
            });
        };
        /* 选项卡增删 */
        // 上传图片控件url
        const onBeforeUpload = async (file: any) => {
            return new Promise((resolve, reject) => {
                const is2M = file.size / 1024 / 1024 <= 10;

                if (!is2M) {
                    ElMessage.warning(`上传的图片最大支持${10}M`);
                    return reject(false);
                }

                const acceptImg = ['image/png', 'image/jpg', 'image/jpeg'];
                if (!acceptImg.includes(file.type)) {
                    ElMessage.warning('请上传支持的图片格式');
                    return reject(false);
                }

                return resolve(true);
            });
        };
        const doUploadCarousel = async (file: UploadRequestOptions, v: any) => {
            const res = await doUpload(file);
            file.file.url = res.url;
            file.file.code = res.code;
            v.picture_url.push(res);
        };
        // 删除图片控件
        const removeCarouselUrl = (file: uploadFile, uploadFiles: uploadFiles, v: any) => {
            // 使用url判断无法准确判断，组件升级后，url是blob形式，通过直接映射上传文件列表做显示
            const index = v.picture_url.findIndex((item: any) => {
                return file.raw ? item.url === file.raw.url : item.url === file.url;
            });
            index >= 0 && v.picture_url.splice(index, 1);
        };
        // 渲染控件卡片
        const renderControlInput = (v: any) => {
            /** 这里是参数的约定，以防止dom混乱看起来有点复杂
             * v @param 这个是当前选项卡的对象
             * item @param 如果当前选项卡是多选，或者下拉，item是属于options_list里的每一项
             * picUrl @param 如果当前选项卡是图片，picUrl是属于picture_url里的每一项
             */
            switch (v.type) {
                case 'textbox':
                case 'mobile':
                case 'email':
                    return <el-input placeholder={v.form_placeholder} readonly></el-input>;
                case 'select':
                case 'radio':
                case 'muti_select':
                    return (
                        <>
                            {v.options_list?.map?.((item: any, op_index: number) => {
                                return (
                                    <div class="add-option">
                                        {!isViewDisabled.value && !v.is_customer_attr && (
                                            <img
                                                onClick={() => removeOption(v, op_index, item)}
                                                src={removeIcon}
                                                alt=""
                                            />
                                        )}
                                        <span
                                            class={item.value ? 'placehoder-style value-style' : 'placehoder-style'}
                                            onClick={() => (item.is_option_write = v.is_customer_attr ? false : true)}>
                                            {item.is_option_write ? (
                                                <el-input
                                                    v-model={item.value}
                                                    placeholder="请输入选项内容"
                                                    maxlength="20"
                                                    show-word-limit
                                                    disabled={isViewDisabled.value}
                                                    v-focus
                                                    onMousedown={handleStopPropagation}
                                                />
                                            ) : (
                                                item.value || '请输入选项内容'
                                            )}
                                        </span>
                                    </div>
                                );
                            })}
                            {!isViewDisabled.value && !v.is_customer_attr && (
                                <div class="add-option add-option-handle" onClick={() => addOption(v)}>
                                    <img src={plusIcon} alt="" />
                                    <span>添加选项</span>
                                </div>
                            )}
                        </>
                    );
                case 'textarea':
                    return <el-input type="textarea" rows={5} placeholder={v.form_placeholder} readonly></el-input>;
                case 'pca':
                    return (
                        <>
                            <el-input placeholder="省/市/区（县）" prefix-icon="location" readonly></el-input>
                        </>
                    );
                case 'date':
                    return <el-date-picker readonly type="date" placeholder={v.form_placeholder} />;
                case 'picture':
                    return (
                        <>
                            <el-upload class="config-card-item__upload" disabled list-type="picture-card">
                                <el-icon onClick={(e: any) => e.stopPropagation()}>
                                    <Plus />
                                </el-icon>
                                <div>点击上传</div>
                            </el-upload>
                            <div class="upload_tip">建议图片大小不超过10M</div>
                        </>
                    );
                case 'carousel':
                    return (
                        <>
                            {v.picture_url.length === 1 ? (
                                <img class="config-card-item__carousel_img" src={v.picture_url[0].url} alt="" />
                            ) : (
                                <el-carousel interval={2000} height="164px" arrow="never">
                                    {v.picture_url?.length ? (
                                        v.picture_url?.map((picUrl: any) => {
                                            return (
                                                <el-carousel-item>
                                                    <img
                                                        class="config-card-item__carousel_img"
                                                        src={picUrl.url}
                                                        alt=""
                                                    />
                                                </el-carousel-item>
                                            );
                                        })
                                    ) : (
                                        <div class="config-card-item__carousel_empty">请上传图片</div>
                                    )}
                                </el-carousel>
                            )}
                            <el-upload
                                file-list={v.picture_url}
                                class={{
                                    'config-card-item__carousel_upload': true,
                                    'config-card-item__carousel_upload__max': v.picture_url.length >= 5
                                }}
                                limit={5}
                                list-type="picture-card"
                                accept=".jpg,.png,.gif,.JPEG"
                                before-upload={onBeforeUpload}
                                disabled={isViewDisabled.value}
                                http-request={(file: UploadRequestOptions) => doUploadCarousel(file, v)}
                                on-remove={(file: uploadFile, uploadFiles: uploadFile) =>
                                    removeCarouselUrl(file, uploadFiles, v)
                                }>
                                <div class="picture-upload-button">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>
                                    <div>点击上传</div>
                                </div>
                            </el-upload>
                            <div class="upload_tip">建议尺寸700*300px，大小不超过10M</div>
                        </>
                    );
                case 'rate':
                    return (
                        <>
                            <el-rate
                                colors={new Array(3).fill('#FF6B00')}
                                class="config-card-item__rate"
                                disabled={isViewDisabled.value}
                            />
                        </>
                    );

                default:
                    return <div>没有找到该控件呢～</div>;
            }
        };
        /* 渲染控件列表 */
        /* 控件列表 */

        /* 拖拽排序 */
        // 初始化拖拽排序功能
        const onMoveFormDataItem: any = inject('onMoveFormDataItem');

        const initSortTable = () => {
            const CardElement = document.querySelector('#config-card-list');
            if (!CardElement) return;
            let SortableBox = new Sortable(CardElement, {
                animation: 100,
                sort: true,
                delay: 0,
                handle: '.drag-item',
                delayOnTouchOnly: false,
                onEnd: (evt: any) => {
                    // const itemEl = evt.item // dragged HTMLElement
                    // evt.to // target list
                    // evt.from // previous list
                    // evt.oldIndex // element's old index within old parent
                    // evt.newIndex // element's new index within new parent
                    // evt.clone // the clone element
                    // evt.pullMode // when item is in another sortable: `"clone"` if cloning, `true` if moving
                    onMoveFormDataItem(evt);
                }
            });
        };
        /* 拖拽排序 */

        /* 封面部分 */
        const fileList = reactive<Array<any>>([]);
        fileList.splice(0, fileList.length);
        const doUploadCover = async (file: UploadRequestOptions) => {
            const res = await doUpload(file);
            fileList.splice(0, fileList.length, res);
        };
        const removeFile = e => {
            e.stopPropagation();
            fileList.splice(0, fileList.length);
        };
        useExpose({
            fileList
        });
        /* 封面部分 */

        /* 页面描述&控件描述，控件标题，选项值，等的输入状态 */
        const hideShowInput = () => {
            showInput.value = false;
            for (const iterator of props.controlCardColumns) {
                iterator.is_desc_write = false;
                iterator.is_title_write = false;
                if (iterator.options_list) {
                    for (const iterator_option of iterator.options_list) {
                        iterator_option.is_option_write = false;
                    }
                }
            }
        };
        const handleStopPropagation = (e: any) => e.stopPropagation();
        onMounted(() => {
            initSortTable();
            document.body.addEventListener('mousedown', hideShowInput);
        });
        onUnmounted(() => {
            document.removeEventListener('mousedown', hideShowInput);
        });
        /* 页面描述&控件描述，控件标题，选项值，等的输入状态 */

        return () => (
            <article class="config-card-form">
                <el-upload
                    file-list={fileList}
                    class="config-card-cover"
                    list-type="picture-card"
                    show-file-list={false}
                    disabled={isViewDisabled.value}
                    accept=".jpg,.png,.JPEG"
                    before-upload={onBeforeUpload}
                    http-request={doUploadCover}>
                    {fileList[0] ? (
                        <div class="config-card-cover__preview">
                            <div class="config-card-cover__preview__content">
                                {!isViewDisabled.value && (
                                    <>
                                        <span class="config-card-cover__preview__icon">
                                            <el-icon>
                                                <RefreshLeft />
                                            </el-icon>
                                            <div>重新上传</div>
                                        </span>
                                        <span onClick={removeFile} class="config-card-cover__preview__icon">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                            <div>删除</div>
                                        </span>
                                    </>
                                )}
                            </div>
                            <img class="cover_img" src={fileList[0].url} alt="" />
                        </div>
                    ) : (
                        <div class="cover-box">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <div>添加封面</div>
                            <div class="cover-tips">图片支持png、jpg、jpeg格式，大小10M以内，建议尺寸600*200</div>
                        </div>
                    )}
                </el-upload>
                <div class="form-config-title">
                    <h4> {basicInfo.value?.activity_name} </h4>
                    <div onClick={() => (showInput.value = true)}>
                        {showInput.value ? (
                            <el-input
                                type="textarea"
                                v-model={form_desc.value}
                                disabled={isViewDisabled.value}
                                modelValue:modifiers={{ trim: true }}
                                placeholder="请输入描述"
                                show-word-limit
                                maxlength="500"
                                v-focus
                                autosize={{ minRows: 4 }}
                                resize="none"
                                onMousedown={handleStopPropagation}
                            />
                        ) : (
                            <div class="main-desc">{form_desc.value || '请输入描述'}</div>
                        )}{' '}
                    </div>
                    {basicInfo.value?.period_type === 2 && <div>截止时间：{basicInfo.value?.effect_date?.[1]}</div>}
                </div>
                {renderShowContentList(props.controlCardColumns)}
                {props.controlCardColumns.length ? (
                    <div class="preview_submit">
                        <el-button type="primary">提交</el-button>
                    </div>
                ) : (
                    <div />
                )}
            </article>
        );
    }
});
